package com.rqf.ls.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.rqf.ls.service.ICommonDataService;
import com.rqf.ls.service.IQuestionAnswerService;
import com.rqf.ls.service.IRegisterService;
import com.server.date.DateType;
import com.server.date.DateUtil;
import com.server.web.DataVector;
import com.server.web.RequestInput;

@Service("QuestionAnwserService")
public class QuestionAnswerService implements IQuestionAnswerService {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private JdbcService jdbcService;
	@Autowired
	private ICommonDataService commonDataService;
	@Autowired
	private IRegisterService registerService;
	
	 /**
	 * 所有问题大类
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月25日
	 */
	@Override
	public List<Map<String, Object>> getBigClass(){
		String sql = "Select * from FUWUBIGCLASS where isable=1 order by id asc";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		return list;
	}	
	
	 /**
	 * 获取小类
	 * @param id
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月25日
	 */
	@Override
	public List<Map<String, Object>> getSmallClass(Integer id){
		String sql = "Select * from FUWUSMALLCLASS where isable=1 %s order by id asc";
		String format = String.format(sql, "and bigclassid="+id);
		List<Map<String, Object>> list = jdbcTemplate.queryForList(format);
		return list;
	}
	
	@Override
	public Boolean add(Map<String, Object> inputMap){
		String sql = "insert into QUESTION (id,createtime,createdate,read,isable,okanwserid,%s) values(QUESTION_SEQUENCE.nextval,'%s',%s,0,'1','0',%s)";
		Set<String> keySet = inputMap.keySet();
		StringBuffer fieldBuffer = new StringBuffer();
		StringBuffer valueBuffer = new StringBuffer();
		for(String key : keySet){
			if (fieldBuffer.length() > 0) {
				fieldBuffer.append(",");
			}
			fieldBuffer.append(key);
			if (valueBuffer.length() > 0) {
				valueBuffer.append(",");
			}
			valueBuffer.append("'").append(inputMap.get(key)).append("'");
		}
		
		//当前时间
		Calendar instance = Calendar.getInstance();
		instance.set(Calendar.HOUR_OF_DAY, 0);
		instance.set(Calendar.MINUTE, 0);
		instance.set(Calendar.SECOND, 0);
		Date time = instance.getTime();
		String format = String.format(sql, fieldBuffer.toString(),
				DateUtil.getDateWithSeconds(new Date()),
				"TO_DATE('"+DateUtil.getDateStr(time,DateType.YYYY_MM_DD)+"','yyyy-MM-dd')",
				valueBuffer.toString());
		
		Boolean isSuccess = true;
		try {
			jdbcTemplate.execute(format);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
		/*inputMap.put("isable", 1);
		inputMap.put("okanwserid", 0);
		inputMap.put("questiontypeid", 1);
		String tableName = "QUESTION";
		String sequenceFun = "QUESTION_SEQUENCE";
		Boolean isSuccess = jdbcService.add(tableName, inputMap, sequenceFun);
		return isSuccess;*/
	}
	@Override
	public Boolean update(Integer id, Map<String, Object> inputMap){
		/*String tableName = "QUESTION";
		String whereStr = "id="+id;
		Boolean isSuccess = jdbcService.update(tableName, inputMap, whereStr);
		return isSuccess;*/
		StringBuffer updateStr = new StringBuffer();
		//String sql = "Update QUESTION set questiontypeid='111',createuser='sbb',content='%s' where id=%s";
		String sql = "Update QUESTION set %s where id=%s";
		Set<String> keySet = inputMap.keySet();
		for(String key : keySet){
			if (updateStr.length() > 0) {
				updateStr.append(",");
			}
			updateStr.append(key).append("='").append(inputMap.get(key)).append("'");
		}
		
		String format = String.format(sql, updateStr.toString(),id);
		Boolean isSuccess = true;
		try {
			jdbcTemplate.execute(format);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	
	@Override
	public Boolean delete(Integer id){
		String sql = "Delete from question where id=%s";
		String format = String.format(sql,id);
		Boolean isSuccess = true;
		try {
			jdbcTemplate.execute(format);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	
	 /**
	 * 获取问题
	 * @param phoneNo
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月28日
	 */
	@Override
	public List<Map<String, Object>> questionList(String phoneNo){
		String sql = "Select * from V_QUESTION_SELECT where createuser='%s' order by createtime desc";
		//String sql = "Select q.*,n.nickname from question q left outer join normaluser n on q.createuser=n.phone where q.isable=1 and q.createuser='%s' order by q.createtime desc";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, phoneNo));
		return list;
	}
	@Override
	public DataVector<Map<String, Object>> questionList(String phoneNo,
			String lawyerNo, RequestInput requestInput){
		String table = "V_QUESTION_SELECT";
		String _whereStr = "";
		if (!StringUtils.isEmpty(phoneNo)) {
			_whereStr = "createuser='"+phoneNo+"'";
		}
		if (!StringUtils.isEmpty(lawyerNo)) {
			if (_whereStr.length() > 0) {
				_whereStr += " and ASKWHOID='"+lawyerNo+"'";
			}else {
				_whereStr = "ASKWHOID='"+lawyerNo+"'";
			}
		}
		String sortStr = "createtime desc";
		DataVector<Map<String, Object>> listData = commonDataService.getListData(table, _whereStr, sortStr, requestInput);
		return listData;
	}
	@Override
	public List<Map<String, Object>> questionList(){
		String sql = "Select q.*,n.nickname from question q left outer join normaluser n on q.createuser=n.phone where q.isable=1 order by q.createtime desc";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		return list;
	}
	@Override
	public List<Map<String, Object>> questionList_Ls(String lawyerPhone){
		String sql = "Select q.*,n.nickname from question q left outer join normaluser n on q.createuser=n.phone where q.isable=1 and q.ASKWHOID='%S' order by q.createtime desc";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, lawyerPhone));
		return list;
	}
	@Override
	public Map<String, Object> questionMap(Integer id){
		String sql = "Select q.*,n.nickname from question q left outer join normaluser n on q.createuser=n.phone where q.isable=1 and q.id=%s";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, id));
		if (list.size() > 0) {
			Map<String, Object> map = list.get(0);
			return map;
		}else {
			return new HashMap<String, Object>();
		}
	}
	 /**
	 * 回复列表
	 * @param id
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月28日
	 */
	@Override
	public List<Map<String, Object>> answerList(Integer id){
		String sql = "Select a.*,l.username from anwser a left outer join lsuser l on a.anwserwho=l.phone where a.isable=1 and a.questionid=%s order by a.createtime asc";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, id));
		return list;
	}
	
	@Override
	public List<Map<String, Object>> getAnswer(String questionId,String lawyerPhone){
		String sql = "Select * from anwser where ANWSERWHO='"+lawyerPhone+"' and QUESTIONID='"+questionId+"'";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		return list;
	}
	
	 /**
	 * 律师回复
	 * @param questionId
	 * @param answerNo
	 * @param inputMap
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月28日
	 */
	@Override
	public Boolean answerAdd(Integer questionId, String answerNo, Map<String, Object> inputMap){
		String sql = "insert into anwser (id,createtime,isable,anwserwho,content,questionid,whoque) values(answer_sequence.nextval,'%s',1,'%s','%s','%s','%s')";
		String format = String.format(sql, DateUtil.getDateWithSeconds(new Date()),answerNo,inputMap.get("content"),questionId,inputMap.get("whoque"));
		Boolean isSuccess = true;
		try {
			jdbcTemplate.execute(format);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	@Override
	public Boolean answerAddVoice(Integer questionId, String answerNo, Map<String, Object> inputMap){
		String sql = "insert into anwser (id,createtime,isable,anwserwho,content,questionid,whoque,type,voice,voicelength) "
				+ "values(answer_sequence.nextval,'%s',1,'%s','%s','%s','%s','%s','%s','%s')";
		String format = String.format(sql, DateUtil.getDateWithSeconds(new Date()),answerNo,inputMap.get("content"),questionId,inputMap.get("whoque"),inputMap.get("type"),inputMap.get("voice"),inputMap.get("voice_length"));
		Boolean isSuccess = true;
		try {
			jdbcTemplate.execute(format);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	 /**
	 * 回答数获取
	 * @param questionId
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月29日
	 */
	@Override
	public Integer answerCount(Integer questionId){
		String sql = "select count(id) from anwser where questionid = %s and isable=1";
		String format = String.format(sql, questionId);
		Integer count = jdbcTemplate.queryForInt(format);
		return count;
	}
	
	 /**
	 * 对问题回答的回复
	 * @param answerId
	 * @param user
	 * @param content
	 * @return
	 * @author ServerZhang
	 * @date 2016年4月5日
	 */
	@Override
	public Boolean evaluateAnswer(Integer answerId,String user,String content){
		String sql = "insert into pingjia (id,createtime,read,isable,pingjiawhoid,anwserid,content) values(PINGJIA_SEQUENCE.nextval,'%s',0,'1','%s','%s','%s')";
		String format = String.format(sql, DateUtil.getDateWithSeconds(new Date()),user,answerId,content);
		Boolean isSuccess = true;
		try {
			jdbcTemplate.execute(format);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	@Override
	public Boolean voiceEvaluateAnswer(Integer answerId,String user,Map<String, Object> inputMap){
		String sql = "insert into pingjia (id,createtime,read,isable,pingjiawhoid,anwserid,type,voice,voicelength) "
				+ "values(PINGJIA_SEQUENCE.nextval,'%s',0,'1','%s','%s','%s','%s','%s')";
		String format = String.format(sql, DateUtil.getDateWithSeconds(new Date()),user,answerId,inputMap.get("type"),inputMap.get("voice"),inputMap.get("voicelength"));
		Boolean isSuccess = true;
		try {
			jdbcTemplate.execute(format);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	 /**
	 * 回答的回复列表
	 * @return
	 * @author ServerZhang
	 * @date 2016年4月5日
	 */
	@Override
	public List<Map<String, Object>> evaluationList(Integer answerId){
		List<Map<String, Object>> returnList = new ArrayList<Map<String,Object>>();
		
		String sql = "Select q.*,n.nickname as nName,l.nickname as lName from pingjia q left outer join normaluser n on q.pingjiawhoid=n.phone left outer join lsuser l on q.pingjiawhoid=l.phone where q.isable=1 %s order by q.createtime asc";
		List<Map<String, Object>> list = null;
		String whereStr = "";
		if (!StringUtils.isEmpty(answerId)) {
			whereStr += " and q.anwserid="+answerId;
		}
		list = jdbcTemplate.queryForList(String.format(sql, whereStr));
		Iterator<Map<String, Object>> iterator = list.iterator();
		while (iterator.hasNext()) {
			Map<String, Object> next = iterator.next();
			Object nObj = next.get("nName");
			Object lObj = next.get("lName");
			next.put("nickname", nObj != null ? nObj : lObj);
		}
		
		Map<String, Object> answerMap = new HashMap<String, Object>();
		String answerSql = "Select a.*,l.username from anwser a left outer join lsuser l on a.anwserwho=l.phone where a.isable=1 and a.id=%s";
		List<Map<String, Object>> answerList = jdbcTemplate.queryForList(String.format(answerSql, answerId));
		if (answerList.size() > 0) {
			answerMap = answerList.get(0);
		}
		returnList.add(answerMap);
		returnList.addAll(list);
		
		return returnList;
	}
	 /**
	 * 有回答的问题列表
	 * @param lawyerNo
	 * @param requestInput
	 * @return
	 * @author ServerZhang
	 * @date 2016年6月27日
	 */
	@Override
	public DataVector<Map<String, Object>> answeredList(String lawyerNo, RequestInput requestInput){
		String table = "V_QUESTION_ANSWERED";
		String _whereStr = "";
		if (!StringUtils.isEmpty(lawyerNo)) {
			_whereStr = "lawyerPhone='"+lawyerNo+"'";
		}
		String sortStr = "createtime desc";
		DataVector<Map<String, Object>> listData = commonDataService.getListData(table, _whereStr, sortStr, requestInput);
		return listData;
	}
	
	@Override
	public Boolean updateAnswer(Integer id, Map<String, Object> inputMap){
		StringBuffer updateStr = new StringBuffer();
		String sql = "Update ANWSER set %s where id=%s";
		Set<String> keySet = inputMap.keySet();
		for(String key : keySet){
			if (updateStr.length() > 0) {
				updateStr.append(",");
			}
			updateStr.append(key).append("='").append(inputMap.get(key)).append("'");
		}
		
		String format = String.format(sql, updateStr.toString(),id);
		Boolean isSuccess = true;
		try {
			jdbcTemplate.execute(format);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
}
